package com.xiaoyu.ambulance.resegence

import `in`.srain.cube.util.CLog
import android.os.DeadObjectException
import android.os.Looper
import com.tencent.bugly.crashreport.CrashReport

class Resurgence {

    companion object {
        private const val TAG = "Resurgence"
        private const val REMOTE_SERVICE_EXCEPTION = "did not then call Service.startForeground()"
        private var fatalListener: FatalOccurListener? = null

        fun start() {
            Global.handler.post(Runnable {
                while (true) {
                    try {
                        Looper.loop()
                    } catch (e: Throwable) {
                        // intercept error here and decide crash or resurgence
                        // like BadTokenException or RemoteServiceException ,we can pull up our app
                        // other fatal problem we just crash it
                        val exString = e.stackTraceString()
                        if (e is UnsatisfiedLinkError && exString.contains("Toast")) {
                            CLog.i(TAG, "load so error ${exString}")
                            CrashReport.postCatchedException(e)
                            handleFatal()
                        } else if (e is DeadObjectException) {
                            CLog.i(TAG, exString)
                            CrashReport.postCatchedException(e)
                            // happen like toast too much
                        } else if (exString.contains(REMOTE_SERVICE_EXCEPTION)) {
                            // pass
                        } else {
                            // quit and go through default process
                            throw  e
                        }
                    }
                }
            })
        }

        fun registerFatalListener(listener: Resurgence.FatalOccurListener) {
            fatalListener = listener
        }

        private fun handleFatal() {
            fatalListener?.onFatalOccur()
        }
    }

    interface FatalOccurListener {
        fun onFatalOccur()
    }
}